前幾天已經學過 Python 的基本語法、List、Dictionary、if、for、Function,以及 CSV 和 JSON。今天繼續往資料處理的方向練習,學習兩個之後爬蟲一定會遇到的東西:Python 模組和例外處理。
在真正做爬蟲的時候,不可能每一次取得的資料都是正常的。例如網站連線失敗、資料格式錯誤、某個欄位沒有資料,這些都有可能讓程式出錯。
所以今天除了學習怎麼使用 Python 的模組,也實際練習讓程式遇到錯誤時不要直接停止。
一、使用 Python Module
Python 有很多內建的模組,可以直接使用,不需要自己從頭寫。
例如今天先使用 random:
import random
number = random.randint(1, 100)
print("隨機數字:", number)
每次執行都有可能得到不同的結果,例如:
隨機數字: 57
也可以使用 datetime 取得目前時間:
import datetime
now = datetime.datetime.now()
print("現在時間:", now)
執行後會看到目前的日期和時間。
這讓我了解到 import 的作用,就是把其他模組的功能拿進自己的程式使用。
二、為什麼需要例外處理?
接下來開始練習 try 和 except。
例如今天有一筆商品價格:
price = "1990"
price = int(price)
print(price)
因為 "1990" 可以轉成整數,所以程式可以正常執行。
但是如果資料變成:
price = "error"
price = int(price)
print(price)
程式就會出現錯誤。
這種情況在爬蟲時其實很常見,因為網站上的資料不一定全部都是我們預期的格式。
所以可以使用:
try:
price = int("error")
print(price)
except:
print("價格資料無法轉換")
這時候程式不會直接中斷,而是顯示:
價格資料無法轉換
三、實際處理商品資料
接下來把前幾天學過的 Dictionary 和 List 拿回來使用。
products = [
{"name": "無線耳機", "price": "1990"},
{"name": "機械鍵盤", "price": "2500"},
{"name": "滑鼠", "price": "error"},
{"name": "USB 麥克風", "price": "1590"}
]
for product in products:
try:
price = int(product["price"])
print(product["name"], "價格:", price)
except:
print(product["name"], "價格資料錯誤")
執行結果:
無線耳機 價格: 1990
機械鍵盤 價格: 2500
滑鼠 價格資料錯誤
USB 麥克風 價格: 1590
這個例子讓我比較能理解為什麼例外處理在資料分析和爬蟲中很重要。
如果沒有 try/except,程式處理到「滑鼠」這筆錯誤資料時就會直接停止。
有了例外處理之後,程式可以跳過錯誤資料,繼續處理後面的資料。
四、搭配 if 做資料判斷
接著把前幾天學過的 if 也加入進來。
products = [
{"name": "手機", "price": "29900"},
{"name": "筆電", "price": "45000"},
{"name": "耳機", "price": "1990"},
{"name": "平板", "price": "error"}
]
for product in products:
try:
price = int(product["price"])
if price >= 10000:
print(product["name"], "價格較高:", price)
else:
print(product["name"], "價格:", price)
except:
print(product["name"], "價格資料有問題")
執行結果:
手機 價格較高: 29900
筆電 價格較高: 45000
耳機 價格: 1990
平板 價格資料有問題
這次就把之前學過的幾個觀念串起來了:
List
↓
Dictionary
↓
for
↓
try / except
↓
if / else
↓
資料處理
我覺得這部分比單獨學每一個語法更有感,因為開始可以看到不同語法如何一起處理實際資料。
五、自己增加錯誤資料測試
最後我自己修改資料,故意加入不同的內容:
products = [
{"name": "手機", "price": "29900"},
{"name": "筆電", "price": "45000"},
{"name": "耳機", "price": "1990"},
{"name": "平板", "price": "error"},
{"name": "鍵盤", "price": "2500"}
]
for product in products:
try:
price = int(product["price"])
if price >= 10000:
print(product["name"], "價格較高:", price)
else:
print(product["name"], "價格:", price)
except:
print(product["name"], "價格資料有問題")
最後得到:
手機 價格較高: 29900
筆電 價格較高: 45000
耳機 價格: 1990
平板 價格資料有問題
鍵盤 價格: 2500
這次的練習讓我比較清楚資料處理不是單純把資料讀進來而已,還需要考慮資料可能不完整或格式錯誤的情況。
尤其之後開始做網路爬蟲,資料是從外部網站取得的,比自己建立的資料更不能保證每一筆都符合預期,因此例外處理會變得很重要。
今天先把這部分的基礎打好,下一步就可以
開始進入 HTTP 和 Requests,
實際讓 Python 對網站發送請求,取得網頁資料。